using System;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;
using Bosphorus.Integration.Jira.Thor.Core.Model.Domain;
using Bosphorus.Integration.Jira.Thor.Dal.Helper;
using Bosphorus.Library.Dao.Facade;
using Bosphorus.Integration.Jira.Thor.Dal.Dao.Model;
using Bosphorus.Integration.Jira.Thor.Core.View.Domain;
using Bosphorus.Integration.Jira.Thor.Dal.Vao.Model;

namespace Bosphorus.Integration.Jira.Thor.Dal.Helper
{
    public partial class DalClientForm : Form
    {
        public DalClientForm()
        {
            InitializeComponent();
            FillQueries();
        }

        private void FillQueries()
        {
            lbQueries.Items.Clear();
            AddQueryModel("Issue - GetAll", Repository.Domain.Live<Issue>.GetAll);
            AddQueryModel("Issue - GetByProject", GetIssuesByProject);
            AddQueryModel("Issue View - GetByProject", GetIssueViewsByProject);
            AddQueryModel("Issue Type - GetAll", Repository.Domain.Live<IssueType>.GetAll);
            AddQueryModel("Issue Type Cache - GetAll", Repository.Domain.Cache<IssueType>.GetAll);
            AddQueryModel("Issue Status - GetAll", Repository.Domain.Live<IssueStatus>.GetAll);
            AddQueryModel("Issue Status Cache - GetAll", Repository.Domain.Cache<IssueStatus>.GetAll);
            AddQueryModel("Projects - All", Repository.Domain.Live<Project>.GetAll);
        }

        private object GetIssuesByProject()
        {
            return Repository.Domain.Live.As<IssueDao>().GetByProject("MFU");
        }

        private object GetIssueViewsByProject()
        {
            return Repository.View.Live<IssueView>.As<IssueVao>().GetByProject("MFU");
        }

        private void lbQueries_DoubleClick(object sender, EventArgs e)
        {
            Cursor current = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            IList data = ((QueryModel)lbQueries.SelectedItem).GetData();
            stopWatch.Stop();

            dgwResult.DataSource = data;
            Text = string.Format("Count: {0}, Time: {1}", data.Count, stopWatch.Elapsed.TotalSeconds);

            Cursor.Current = current;
        }

        private void AddQueryModel(string queryName, NonParameteredQueryModel.NonParameterdDelegate delegation)
        {
            lbQueries.Items.Add(new NonParameteredQueryModel(queryName, delegation));
        }

        private void AddQueryModel(string queryName, ParameteredQueryModel.ParameterdDelegate delegation, params object[] parameters)
        {
            lbQueries.Items.Add(new ParameteredQueryModel(queryName, delegation, parameters));
        }
    }
}